#include "../include/TcpConnection.h"
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <errno.h>
#include <cstring>

TcpConnection::TcpConnection(int fd) : _fd(fd)
{
    std::cout << "创建TCP连接，fd: " << _fd << std::endl;
}

TcpConnection::~TcpConnection()
{
    close();
    std::cout << "TCP连接销毁，fd: " << _fd << std::endl;
}

void TcpConnection::send(const std::string &message)
{
    if (_fd < 0)
    {
        std::cerr << "错误: 连接已关闭，无法发送数据" << std::endl;
        return;
    }

    size_t total_sent = 0;
    size_t remaining = message.size();

    while (total_sent < message.size())
    {
        ssize_t sent = ::send(_fd, message.data() + total_sent, remaining, 0);

        if (sent < 0)
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                // 非阻塞socket，稍后重试
                continue;
            }
            else
            {
                std::cerr << "发送数据错误: " << strerror(errno) << std::endl;
                break;
            }
        }
        else if (sent == 0)
        {
            std::cout << "连接已关闭" << std::endl;
            break;
        }

        total_sent += sent;
        remaining -= sent;
    }

    std::cout << "发送数据: " << total_sent << " 字节" << std::endl;
}

std::string TcpConnection::receive()
{
    if (_fd < 0)
    {
        std::cerr << "错误: 连接已关闭，无法接收数据" << std::endl;
        return "";
    }

    char buffer[1024];
    std::string data;

    // 设置为非阻塞模式读取所有可用数据
    while (true)
    {
        ssize_t received = recv(_fd, buffer, sizeof(buffer) - 1, 0);

        if (received > 0)
        {
            buffer[received] = '\0';
            data.append(buffer, received);
            std::cout << "📥 接收数据块: " << received << " 字节" << std::endl;

            // 如果接收的数据少于缓冲区，说明数据已经接收完毕
            if (static_cast<size_t>(received) < sizeof(buffer) - 1)
            {
                break;
            }
        }
        else if (received == 0)
        {
            std::cout << "🔌 对端关闭连接" << std::endl;
            break;
        }
        else
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                // 非阻塞socket，没有更多数据
                break;
            }
            else
            {
                std::cerr << "接收数据错误: " << strerror(errno) << std::endl;
                break;
            }
        }
    }

    std::cout << "✅ 总共接收: " << data.size() << " 字节" << std::endl;
    return data;
}

void TcpConnection::close()
{
    if (_fd >= 0)
    {
        ::close(_fd);
        _fd = -1;
        std::cout << "关闭TCP连接" << std::endl;
    }
}